/**
 * 起重设备数据展示 craneDataShow.js
 * 版本号： v1.0.0
 */
$(function () {
    //设置body宽度，避免样式变形
    var width = document.body.offsetWidth;
    if(width < 1100){
        width = 1150;
    }
    $('#craneDataBodyId_').width(width);

    var deviceNumber = $('#deviceId_').text();
    if(deviceNumber != "无" && deviceNumber != ""){
        //初始化实时数据进度条
        $(".dy-progressbar").dyProgressBar();
        nowDataStandard(deviceNumber);
    }
});

/**
 * 起重设备选择
 * @param deviceNumber
 */
function deviceClick(device){
    //获取起重设备型号
    var deviceNumber = $('.deviceNumberInner', device).text();
    //更新最左侧设备信息
    updateBasicInfo(deviceNumber);
    //历史数据时间单位置为时
    $(".timeBgStyle").css("background-color","#FFFFFF");
    $("#hour_").css("background-color","skyblue");
    //历史数据类型置为力矩
    $(".craneTypeLi").css("background-color","#FFFFFF");
    $("#MomentPercent").css("background-color","skyblue");
    nowDataStandard(deviceNumber);
}

/**
 * 时间选择
 * @param times
 */
function timeSelect(times){
    $(".timeBgStyle").css("background-color","#FFFFFF");
    times.style.background="skyblue";
    var timeType = times.getAttribute("id");
    //获取聚合单位
    var resample = getResample(timeType);
    //起重机械设备编号
    var deviceNumber = $('#deviceId_').text();
    if(deviceNumber != "无" && deviceNumber != ""){
        //时间选择框所选的开始与结束时间
        var startTime = $('#startTime_').datetimebox('getValue');
        var endTime = $('#endTime_').datetimebox('getValue');
        //获取选中的起重机械指标类型
        var craneTypeArr = document.getElementsByClassName('craneTypeLi');
        var craneType= "";
        for(var i=0;i<craneTypeArr.length;i++){
            var bg = craneTypeArr[i].style['background-color'];
            if(bg == "skyblue"){
                craneType = craneTypeArr[i].getAttribute("id");
            }
        }
        craneTypeEchart(deviceNumber,startTime,endTime,resample,craneType);
    }
}

/**
 * 起重机械参数选择
 * @param craneType
 */
function craneTypeSelect(craneType){
    $(".craneTypeLi").css("background-color","#FFFFFF");
    craneType.style.background="skyblue";
    var craneTypeId = craneType.getAttribute("id");
    var deviceNumber = $('#deviceId_').text();
    //更新历史数据中的标题
    var stanardTitle = getStandardTitle(craneTypeId);
    $('#standardTitle_').text(stanardTitle);
    //选择类型时聚合单位以小时为基础
    if(deviceNumber != "无" && deviceNumber != ""){
        //时间选择框所选的开始与结束时间
        var startTime = $('#startTime_').datetimebox('getValue');
        var endTime = $('#endTime_').datetimebox('getValue');
        //获取选中的扬尘类型
        var timeIdArr = document.getElementsByClassName('timeBgStyle');
        //默认为小时
        var timeType= "hour_";
        for(var i=0;i<timeIdArr.length;i++){
            var bg = timeIdArr[i].style['background-color'];
            if(bg == "skyblue"){
                timeType = timeIdArr[i].getAttribute("id");
            }
        }
        var resample = getResample(timeType);
        craneTypeEchart(deviceNumber,startTime,endTime,resample,craneTypeId);
    }
}

/**
 * 根据时间id获取聚合单位
 * @param timeType
 * @returns {string}
 */
function getResample(timeType){
    var resample = "";
    switch (timeType) {
        case "second_":
            resample = "S";
            break;
        case "minute_":
            resample = "T";
            break;
        case "hour_":
            resample = "H";
            break;
        case "day_":
            resample = "D";
            break;
        case "weekend_":
            resample = "W";
            break;
        case "month_":
            resample = "M";
            break;
        case "year_":
            resample = "Y";
            break;
    }
    return resample;
}

/**
 * 获取历史数据标题
 * @param type
 */
function getStandardTitle(type){
    var standardTitle = "";
    switch (type) {
        case "MomentPercent":
            standardTitle = "起重机械力矩走势图";
            break;
        case "Radius":
            standardTitle = "起重机械幅度走势图";
            break;
        case "LoadData":
            standardTitle = "起重机械吊重走势图";
            break;
        case "Height":
            standardTitle = "起重机械高度走势图";
            break;
        case "ObliqueAngle":
            standardTitle = "起重机械倾角走势图";
            break;
        case "WindSpeed":
            standardTitle = "起重机械风速走势图";
            break;
        case "Angle":
            standardTitle = "起重机械回转角走势图";
            break;
    }
    return standardTitle;
}

/**
 * 更新基础数据
 * @param deviceNumber
 */
function updateBasicInfo(deviceNumber){
    $.ajax({
        url: CONTEXT_PATH + "/craneDataShow/craneProject.do?deviceId=" + deviceNumber ,
        type: "get",
        success: function (data) {
            if(null != data){
                var deviceId = data.deviceId;
                if(data.craneStandard == null){
                    setBasicInfo(deviceId,null,null,null,null,null,null);
                }else{
                    var csVer = data.craneStandard.csVer;
                    var capacity = data.craneStandard.capacity;
                    var maxRange = data.craneStandard.maxRange;
                    var torque = data.craneStandard.torque;
                    var liftHeight = data.craneStandard.liftHeight;
                    var windSpeed = data.craneStandard.maxWindSpeed;
                    setBasicInfo(deviceId,csVer,capacity,maxRange,torque,liftHeight,windSpeed);
                }
            }else{
                setBasicInfo(null,null,null,null,null,null,null);
            }
        },
        error:function () {
            setBasicInfo(null,null,null,null,null,null,null);
        }
    })
}

/**
 * 设置基本信息
 * @param deviceId
 * @param csVer
 * @param capacity
 * @param maxRange
 * @param torque
 * @param liftHeight
 * @param windSpeed
 */
function setBasicInfo(deviceId,csVer,capacity,maxRange,torque,liftHeight,windSpeed){
    $('#deviceId_').text(deviceId == null?"无":deviceId);
    $('#csVer_').text(csVer == null?"无":csVer);
    $('#capacity_').text(capacity == null?"无":capacity);
    $('#maxRange_').text(maxRange == null?"无":maxRange);
    $('#ratedTorque_').text(torque == null?"无":torque);
    $('#liftHeight_').text(liftHeight == null?"无":liftHeight);
    $('#windSpeedHd_').text(windSpeed == null?"无":windSpeed);
}


/**
 * 更新数据
 * @param deviceId
 */
var getDataTimer = "";
function nowDataStandard(deviceNumber){
    //更新历史数据起重机械指标
    var startTime = "";
    var endTime = "";
    var resample = "H";
    var craneType = "MomentPercent";
    craneTypeEchart(deviceNumber,startTime,endTime,resample,craneType);
    //每十秒轮询查询各指标实时数据以及警报数据
    pollingData(deviceNumber);
    //清除已存在的定时
    if(getDataTimer != ""){
        clearInterval(getDataTimer);
    }
    getDataTimer = setInterval(function(){pollingData(deviceNumber);}, 10000);
}

/**
 * 起重机械指标及以及警报数据
 */
function pollingData(deviceNumber){
    //起重机械实时数据
    var craneStandValErr = ["","","","","","",""];
    $.ajax({
        url: CONTEXT_PATH + "/apiUtil/doGet.do",
        data: {
            url: "http://store.d.guijianyun.com:8000/devices/"+deviceNumber+"/latest"
        },
        type: "get",
        success: function (data) {
            if (data) {
                var jsonObj =  eval('(' + data + ')');
                if(null == jsonObj.data){
                    refNowData(craneStandValErr,"");
                    return;
                }
                //最近更新时间
                var date = new Date(jsonObj.created_at);
                var localeString = date.toLocaleString('en-CHS', { hour12: false });
                date = localeString;
                var craneStandValCor = [jsonObj.data.MomentPercent+"",jsonObj.data.Radius+"",jsonObj.data.LoadData+"",jsonObj.data.Height+"",
                    jsonObj.data.ObliqueAngle+"",jsonObj.data.WindSpeed+"",jsonObj.data.Angle+""];
                refNowData(craneStandValCor,date);
            }
        },
        error:function () {
            refNowData(craneStandValErr,"");
        }
    });
    //起重机械警报
    $.ajax({
        url: CONTEXT_PATH + "/craneDataShow/craneAlarm.do",
        data: {
            deviceId: deviceNumber
        },
        type: "get",
        success: function (data) {
            $(".alarm-table").find("tr").each(function() {
                if($(this).attr("class") == "alarm-args"){
                    $(this).remove();
                }
            });
            if(data && data[0] && data[0].alarmTime){
                if(data.length > 0){
                    for(var i = 0; i < data.length; i++){
                        var newTr = '<tr class="alarm-args">'+
                            '<td>'+data[i].alarmContent+'</td>'+
                            '<td>'+data[i].alarmTime+'</td>'+
                            '<td>'+data[i].alarmStatus+'</td>'+
                            '</tr>';
                        $(".alarm-table").append(newTr);
                    }
                }
            }
        }
    })
}

/**
 * 更新实时数据
 * @param craneStandValArr
 */
function refNowData(craneStandValArr,date){
    //更新数据时间
    $('#updateTime_').text(date==""?"无":date);
    //更新实时数据起重机械指标
    var nowDataDiv = "无";
    var craneStandIdArr = ["relTorque_","relRange_","relWeight_","relHeight_","relDipAngle_","relWindSpeed_","relReturnAngle_"];
    for(var i=0;i<craneStandValArr.length;i++){
        if(craneStandValArr[i]==""||craneStandValArr[i]==null||craneStandValArr[i]=="undefined"){
            $('#'+craneStandIdArr[i]).html(nowDataDiv);
            $('#'+craneStandIdArr[i]).parent('.craneArgs').find(".dy-progressbar").dyProgressBar("show", 0);
        }else{
            if(i == 0){
                setCaraneProgressbar("ratedTorque_",craneStandValArr[0],craneStandIdArr[0]);
            }
            if(i == 1){
                setCaraneProgressbar("maxRange_",craneStandValArr[1],craneStandIdArr[1]);
            }
            if(i == 2){
                setCaraneProgressbar("capacity_",craneStandValArr[2],craneStandIdArr[2]);
            }
            if(i == 3){
                setCaraneProgressbar("liftHeight_",craneStandValArr[3],craneStandIdArr[3]);
            }
            if(i == 4){
                setCaraneProgressbar("",craneStandValArr[4],craneStandIdArr[4]);
            }
            if(i == 5){
                setCaraneProgressbar("windSpeedHd_",craneStandValArr[5],craneStandIdArr[5]);
            }
            if(i == 6){
                setCaraneProgressbar("",craneStandValArr[6],craneStandIdArr[6]);
            }
        }
    }
}

/**
 * 设置起重机械实时数据及进度条
 * @param ratedValue
 * @param relValue
 * @param isAngle
 */
function setCaraneProgressbar(ratedValueId,relValue,relValueId){
    var percent = 0;
    //判断是角度或倾斜角
    if(ratedValueId == ""){
        percent = relValue / (360 *100);
    }else{
        var standTorque = 1;
        if("windSpeedHd_" == ratedValueId){
            standTorque = $('#'+ratedValueId).val() == "无"?1:$('#'+ratedValueId).val();
        }else{
            standTorque = $('#'+ratedValueId).text() == "无"?1:$('#'+ratedValueId).text();
        }
        percent = relValue / (standTorque * 100);
    }
    if(percent < 0){
        percent = 0
    }else if(percent > 100){
        percent = 100
    }else{
        percent = percent.toFixed(2);
    }
    $('#'+relValueId).text(relValue);
    $('#'+relValueId).parent('.craneArgs').find(".dy-progressbar").dyProgressBar("show", percent);
}

/**
 * 起重机械历史数据更新
 * @param deviceNumber
 * @param startTime
 * @param endTime
 * @param resample
 * @param value
 */
function craneTypeEchart(deviceNumber,startTime,endTime,resample,value) {
    //起重机械历史值url
    var dustUrl = "http://store.d.guijianyun.com:8000/service/calc?";
    var params = "device_id=" + deviceNumber;
    var start = "";
    //开始时间为空，获取当天0点的毫秒数作为开始时间
    if(startTime == null || startTime == ""){
        var date = new Date();
        var year = date.getFullYear();
        var month = date.getMonth()+1;
        var day = date.getDate();
        var startDate= new Date(year+"/"+month+"/"+day);
        start = startDate.getTime();
    }else{
        start = (new Date(startTime)).getTime();
    }
    if(endTime == null || endTime == ""){
        params = params + "&start=" + start + "&resample=" + resample;
    }else{
        var endTimeHs = (new Date(endTime)).getTime();
        params = params + "&start=" + start + "&end=" + endTimeHs + "&resample=" + resample;
    }
    params = params + "&value=" + value;
    dustUrl = dustUrl + params;
    $.ajax({
        url: CONTEXT_PATH + "/apiUtil/doGet.do",
        data: {
            url: dustUrl
        },
        type: "get",
        success: function (data) {
            if(data) {
                var jsonObj = eval('(' + data + ')');
                if(jsonObj){
                    var timeArr = [];
                    var dataArr = [];
                    for(var time in jsonObj){
                        var newTime = new Date(parseInt(time));
                        var timeData = calDateType(newTime,resample);
                        timeArr.push(timeData);
                        dataArr.push(Number(jsonObj[time]).toFixed(2));
                    }
                    getCraneTypeEchart(value,timeArr,dataArr);
                }
            }else{
                getCraneTypeEchart(value,new Array(),new Array());
            }
        },
        error:function () {
            getCraneTypeEchart(value,new Array(),new Array());
        }
    });
}

/**
 * 获取历史数据统计图
 * @param craneType
 * @param xData
 * @param yData
 */
function getCraneTypeEchart(craneType,xData,yData){
    //重定图形y轴值
    var yMax = 1;
    var yMaxValue = findMaxYdata(yData);
    var standardTitle = "";
    var unit = "";
    switch (true) {
        case craneType=="MomentPercent":
            if(yMaxValue < 5){
                yMax = 5;
            }else if(yMaxValue >= 5 && yMaxValue < 20){
                yMax = 20;
            }else if(yMaxValue >= 20 && yMaxValue < 50){
                yMax = 50;
            }else{
                yMax = 100;
            }
            unit = "%";
            standardTitle = "力矩";
            break;
        case craneType=="Radius":
            yMax = 10;
            unit = "m";
            standardTitle = "幅度";
            break;
        case craneType=="LoadData":
            yMax = 10;
            unit = "t";
            standardTitle = "吊重";
            break;
        case craneType=="Height":
            if(yMaxValue < 10){
                yMax = 10;
            }else if(yMaxValue >= 10 && yMaxValue < 50){
                yMax = 50;
            }else{
                yMax = 100;
            }
            unit = "m";
            standardTitle = "高度";
            break;
        case craneType=="ObliqueAngle":
            if(yMaxValue < 10){
                yMax = 10;
            }else if(yMaxValue >= 10 && yMaxValue < 50){
                yMax = 50;
            }else if(yMaxValue >= 50 && yMaxValue < 100){
                yMax = 100;
            }else{
                yMax = 360;
            }
            unit = " °";
            standardTitle = "倾角";
            break;
        case craneType=="WindSpeed":
            if(yMaxValue < 5){
                yMax = 5;
            }else if(yMaxValue >= 5 && yMaxValue < 20){
                yMax = 20;
            }else{
                yMax = 50;
            }
            unit = "m/s";
            standardTitle = "风速";
            break;
        case craneType=="Angle":
            if(yMaxValue < 10){
                yMax = 10;
            }else if(yMaxValue >= 10 && yMaxValue < 50){
                yMax = 50;
            }else if(yMaxValue >= 50 && yMaxValue < 100){
                yMax = 100;
            }else{
                yMax = 360;
            }
            unit = " °";
            standardTitle = "回转角";
            break;
    }
    //构建图形
    var myChart1 = echarts.init(document.getElementById('craneTypeEchart_'));
    window.addEventListener("resize", function () {
        myChart1.resize();
    });
    var option = {
        toolbox: {
            right: 27,
            feature: {
                magicType: {
                    type: ['line', 'bar']
                }
            }
        },
        grid:{
            x:20,
            y:40,
            x2:45,
            y2:20,
            show:true,  //表示开启
            containLabel:50,
        },
        xAxis: {
            data: xData,
            splitLine: {
                lineStyle: {
                    color: '#D4DFF5'
                }
            },
            axisLine: {
                lineStyle: {
                    color: '#289bd3',
                    width: 2
                }
            },
            axisLabel: {
                textStyle: {
                    fontSize: 14,
                    color: '#333'
                }
            }
        },
        yAxis: {
            name: '单位('+unit+')',
            nameTextStyle:{
                padding:[3, 4, 5, 40]
            },
            axisLine: {
                lineStyle: {
                    color: '#289bd3',
                    width: 2
                }
            },
            axisLabel: {
                textStyle: {
                    fontSize: 14,
                    color: '#333'
                }
            },
            max: yMax
        },
        tooltip: {
            trigger: 'axis'
        },
        series: [{
            name: standardTitle + '数据',
            type: 'line',
            smooth: true,
            data: yData,
            itemStyle: {
                normal:{
                    color: '#2ec7c9'
                }

            },
            lineStyle:{
                width:5
            },
            markPoint: {
                itemStyle: {
                    normal:{
                        color: '#2ec7c9'
                    }

                },
                data: [{
                    type: 'max',
                    name: '最大值'
                }, {
                    type: 'min',
                    name: '最小值'
                }]
            },
            markLine: {
                data: [
                    {type: 'average', name: '平均值'}
                ]
            }
        }]
    };
    myChart1.setOption(option);
}

/**
 * 计算时间类型
 * @param time
 * @param type
 */
function calDateType(time,type){
    var timeVal = "";
    var year = time.getFullYear();
    var month = time.getMonth()+1;
    var day = time.getDate();
    var hour = time.getHours();
    var minute = time.getMinutes();
    var second = time.getSeconds();
    switch(type){
        case "S":
            timeVal = hour + ":" + minute + ":" + second;
            break;
        case "T":
            timeVal = hour + ":" + minute;
            break;
        case "H":
            timeVal = hour;
            break;
        case "D":
            timeVal = day;
            break;
        case "W":
            timeVal = month + "-" + day;
            break;
        case "M":
            timeVal = month;
            break;
        case "Y":
            timeVal = year;
            break;
    }
    return timeVal;
}

/**
 * 查询最大值
 * @param yData
 */
function findMaxYdata(yData) {
    var maxValue = 1;
    if(yData.length > 0){
        for(var i=0;i<yData.length;i++){
            if(null != yData[i] && "" != yData[i]){
                var ydata = parseFloat(yData[i]);
                if(ydata > maxValue){
                    maxValue = ydata;
                }
            }
        }
    }
    return maxValue;
}
